<?php require_once("../includes/initializeSession.php"); ?>
<?php
if (!isset($_SESSION['admin'])) {
    header('Location: agentLogin.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>  
    <title>ר.א צ'ק אין - פתרונות ביטוח</title>
    <head>
<?php require_once("../includes/cssAndJsAdmin.php"); ?>
                    <script type="text/javascript">
                        
                     
                        //style="vertical-align:top"
var get_Mehiron_Names_With_PricesJson;
                        $(document).ready(function() {

                            var payment_type = {
                                "מזומן": "מזומן",
                                "אשראי": "אשראי",
                                "העברת בנקאית": "העברת בנקאית",
                                "צ'קים": "צ'קים"}

                            // calander stuff
                            var person_number_trigger = 0;
                            var checkInDate;
                            var checkOutDate;
                            var checkDate;
                            function setStartDateForEndDate() {
                                var temp = checkInDate.datepicker('getDate');
                                if (temp)
                                    return {minDate: temp};
                                else
                                    return {};

                            }
                            function setEndDateForStartDate() {

                                var temp = checkOutDate.datepicker('getDate');
                                if (temp)
                                    return {maxDate: temp};
                                else
                                    return {};

                            }
                            function refreshPrice() {
                                
                                 // var manuyPriceForYear=$(this).val();
                                 
                                          var manuyPriceForYear=get_Mehiron_Names_With_PricesJson.prices[$("#product_desc").val()];
                                            if (Date.parse($("#from_2").val()).add(6).month().compareTo(Date.parse($("#until").val())) === -1 || $("#state").val()=="החלפה")
                                            {
                                                 //jqgridFormMassage("יותר מחצי שנה")
                                                var a = Date.parse($("#from_2").val()).add(1).year();
                                                var b = Date.parse($("#from_2").val());
                                                var c =Date.parse($("#until").val());
                                                var manuyDuration = new TimeSpan(c - b);
                                                var daysInYear = new TimeSpan(a - b);

                                                $("#product_price").val(manuyPriceForYear / 365 * (manuyDuration.days));
                                                $("#total_payment").val(manuyPriceForYear / 365 * (manuyDuration.days));
                                                $("#agent_commission").val("0");
                                            }
                                            else
                                            {
                                                //jqgridFormMassage("פחות מחצי שנה")
                                                $("#product_price").val(manuyPriceForYear/2);
                                                $("#total_payment").val(manuyPriceForYear/2);
                                            }
                               /* var startDate = checkInDate.datepicker('getDate');
                                var EndDate = checkOutDate.datepicker('getDate');
                                if (startDate > EndDate)
                                    checkOutDate.val('');*/
                            }
                            // end calander stuff


                            //---------manuim jq grid

                                    $("#manuimList").jqGrid({
                                        url: "../gridFunctions/manuimActions.php",
                                        editurl: "../gridFunctions/manuimActions.php",
                                        direction: 'rtl',
                                        async: false,
                                        datatype: 'json',
                                        
                                        loadError: function(xhr, st, err) {
                                            $($("[id=gs_person_number]")[1]).attr("disabled", "disabled")
                                        },
                                        loadComplete: function() {

                                            // 	alert("Sdf");
                                            $($("[id=gs_person_number]")[1]).attr("disabled", "disabled")
                                            // here was ajax
                                            
                                           


                                        },
                                        pager: '#manuimPager',
                                        onSelectRow: function(rowid) {
                                            if (getSelectedCellManuim("last") == 1) {
                                                enableBTN();
                                            } else {
                                                disableBTN()
                                            }
//                                             if (getSelectedCellManuim("paymen_type") == "צ'קים") {
//                                                $("#checksContainer").show();
//                                            } else {
//                                                $("#checksContainer").hide();
//                                            }
                                            $("#checksList").setGridParam({'postData': {manuy2client_manuy_number: getSelectedCellManuim("manuy_number")}});
                                            jQuery("#checksList").trigger('reloadGrid');
                                            
                                            
                                            $("#cashList").setGridParam({'postData': {manuy2client_manuy_number: getSelectedCellManuim("manuy_number")}});
                                            jQuery("#cashList").trigger('reloadGrid');
                                            
                                            
                                        },
                                        colNames: ['מספר שורה', 'מספר מנוי', 'תאריך אסמכתא', 'מצב', 'סוכן', 'לקוח', 'מתאריך', 'עד תאריך', 'סוג רכב', 'קוד דגם', 'מס רישוי', 'שנת ייצור', 'סוג מנוי', 'מחיר מנוי', 'באמצעות', 'עמלת סוכן', 'ע"ח עמלה', 'סה"כ', 'שולם?', 'אחרון', 'תשלום לסוכן', 'שולם ס.מ', 'ת.עמלה'],
                                        colModel: [
                                            {name: 'manuy_row', hidden: true, index: 'manuy_row', width: 60, editable: true, align: 'right', editoptions: {readonly: "readonly"}},
                                            {name: 'manuy_number', index: 'manuy_number', width: 100, editable: true, align: 'right', editoptions: {readonly: "readonly"}},
                                            {name: 'create_2', index: 'create_2', width: 130, editable: true, align: 'right', editoptions: {readonly: "readonly"}},
                                            {name: 'state', index: 'state', width: 60, editable: true, align: 'right', editoptions: {readonly: "readonly"}},
                                            {name: 'agent_person_number', index: 'agent_person_number', width: 60, editable: true, align: 'right', editoptions: {readonly: "readonly"}},
                                            {name: 'person_number', index: 'person_number', width: 120, editable: true, align: 'right', editoptions: {readonly: "readonly"}},
                                            {name: 'from_2', index: 'from_2', width: 110, editable: true, align: 'right'},
                                            {name: 'until', index: 'until', width: 110, editable: true, align: 'right'},
                                            {name: 'manufacturer', index: 'manufacturer', width: 70, editable: true, align: 'right'},
                                            {name: 'model', index: 'model', width: 70, editable: true, align: 'right'},
                                            {name: 'license_plate', index: 'license_plate', width: 80, editable: true, align: 'right'},
                                            {name: 'production_year', index: 'production_year', width: 80, editable: true, align: 'right'},
                                            {name: 'product_desc', index: 'product_desc', width: 450, editable: true, edittype: "select",
                            editoptions: {
                                dataEvents: [
                                    {
                                        type: 'change',
                                        fn: function(e) {
                                      refreshPrice();
                                        }
                                    }
                                ]
                            }
                        },
                                            {name: 'product_price', editoptions: {readonly: "readonly"}, index: 'product_price', width: 80, editable: true, align: 'right'},
                                            {name: 'paymen_type', index: 'paymen_type', width: 90, editable: true, align: 'right', edittype: "select", editoptions: {value: payment_type}},
                                            {name: 'agent_commission', index: 'agent_commission', width: 90, editable: true, align: 'right'},
                                            {name: 'from_agent_commission', index: 'from_agent_commission', width: 90, editable: true, align: 'right', edittype: 'checkbox', formatter: "checkbox", editoptions: {value: "1:0"}},
                                            {name: 'total_payment', index: 'total_payment', width: 60, editable: true, align: 'right',
                                                editoptions: {
                                                    dataEvents: [
                                                        {
                                                            type: 'change',
                                                            fn: function(e) {

                                                                $("#agent_commission").val($("#total_payment").val() - $("#product_price").val());


                                                            }
                                                        }
                                                    ]
                                                }
                                            },
                                            {name: 'shulam', index: 'shulam', width: 60, editable: true, align: 'right', edittype: 'checkbox', formatoptions: {disabled: true}, formatter: "checkbox", editoptions: {value: "1:0"}},
                                            {name: 'last', hidden: true, index: 'last', width: 60, editable: true, align: 'right', edittype: 'checkbox',formatoptions: {disabled: true}, formatter: "checkbox", editoptions: {value: "1:0"}},
                                            {name: 'shulamToAgent', index: 'shulamToAgent', width: 110, editable: true, align: 'right', edittype: 'checkbox',formatoptions: {disabled: true}, formatter: "checkbox", editoptions: {value: "1:0"}},
                                            {name: 'shulamToMetriaAgent', index: 'shulamToMetriaAgent', width: 90, editable: true, align: 'right', edittype: 'checkbox', formatoptions: {disabled: true}, formatter: "checkbox", editoptions: {value: "1:0"}},
                                            {name: 'agentAmlaDate', index: 'agentAmlaDate', width: 90, editable: true, align: 'right'}
                                    ],
                                        rowNum: 20,
                                        rowList: [5, 10, 20, 50],
                                        sortname: 'person_number',
                                        sortorder: "desc",
                                        mtype: "POST",
                                        //loadonce: true,
                                        postData: {oper: 'viewManuims'},
                                        viewrecords: true,
                                        imgpath: '../../Scripts/css/Aristo/images',
                                        
                                        
                                        
                                     
                                        height: "100%"
                                    }); // -- end of   $("#list").jqGrid({


                                    $("#manuimList").jqGrid('navGrid', '#manuimPager', { edit: true, add: false, del: true, refresh: true, closeAfterAdd: true, reloadAfterSubmit: true, search: false},
                                    // Edit dialog parameters
                                    {
                                        recreateForm: true,
                                        width: 450,
                                        reloadAfterSubmit: true,
                                        closeAfterEdit: true,
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            return {product_desc: $("#product_desc option:selected").text()};
                                        },
                                        beforeShowForm: function() {


                                            //-----------calander

                                            
                                            checkInDate = $('#from_2');
                                            checkOutDate = $('#until');
                                            checkAmlaDate = $('#agentAmlaDate');

                                            checkInDate.datepicker({
                                                beforeShow: setEndDateForStartDate,
                                                onClose: refreshPrice,
                                                dateFormat: 'yy-mm-dd',
                                                
                                                        //  dateFormat: 'dd/mm/yy'
                                            });

                                            checkOutDate.datepicker({
                                                beforeShow: setStartDateForEndDate,
                                                onClose: refreshPrice,
                                                dateFormat: 'yy-mm-dd',
                                                        //  dateFormat: 'dd/mm/yy'
                                            });
                                            
                                            checkAmlaDate.datepicker({
                                                dateFormat: 'yy-mm-dd',
                                                        //  dateFormat: 'dd/mm/yy'
                                            });

                                            checkInDate.datepicker('setDate', new Date());
                                            checkOutDate.datepicker('setDate', new Date());


                                            //--calander
                                          //  refreshPrice();
                                            //$("#product_price").val($("#product_desc").val());

                                         
                                         /*   $("#shulam").attr("disabled", true);
                                            $("#shulamToAgent").attr("disabled", true);
                                            $("#shulamToMertiaAgent").attr("disabled", true);*/
                                            //  agent_person_number
                                            //  person_number


                                        },
                                        afterSubmit: function(response, postdata)
                                        {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("פרטי המנוי התעדכנו בהצלחה")
                                            }
                                            else
                                            {

                                                success = false;
                                                alert("פרטי המנוי לא התעדכנו בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }
                                    },
                                    // Add dialog parameters
                                    {
                                        recreateForm: true,
                                        width: 450,
                                        reloadAfterSubmit: true,
                                        closeAfterAdd: true,
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            return {product_desc: $("#product_desc option:selected").text()};
                                        },
                                         afterShowForm: function() {
                                    
                                         if (!getSelectedCell("person_number"))
                                            {
                                             
                                               $.jgrid.hideModal("#editmodmanuimList", {gbox: "#gbox_manuimList"});
                                                alert("אתה חייב לבחור לקוח על מנת להוסיף לו מנוי");
    
                                            }
                                    
                                        },
                                        beforeShowForm: function() {

                                             if (!getSelectedCell("person_number"))
                                            {
                                               
                                            }
                                            else
                                            {
                                                //-----------calander
                                                var yearFromNow = new Date();
                                                yearFromNow.setFullYear(yearFromNow.getFullYear() + 1);

                                                checkAmlaDate = $('#agentAmlaDate');
                                                checkInDate = $('#from_2');
                                                checkOutDate = $('#until');

                                                checkInDate.datepicker({
                                                beforeShow: setEndDateForStartDate,
                                                onClose: refreshPrice,
                                                dateFormat: 'yy-mm-dd',
                                                
                                                        //  dateFormat: 'dd/mm/yy'
                                                });

                                                checkOutDate.datepicker({
                                                    beforeShow: setStartDateForEndDate,
                                                    onClose: refreshPrice,
                                                    dateFormat: 'yy-mm-dd',
                                                            //  dateFormat: 'dd/mm/yy'
                                                });
                                                
                                                checkAmlaDate.datepicker({
                                                dateFormat: 'yy-mm-dd',
                                                        //  dateFormat: 'dd/mm/yy'
                                                 });

                                                checkInDate.datepicker('setDate', new Date());
                                                checkOutDate.datepicker('setDate', yearFromNow);


                                                //--calander

                                                //$("#product_price").val($("#product_desc").val());
                                                refreshPrice();
                                             
                                                $("#person_number").val(getSelectedCell("person_number"));
                                                $("#state").val("פעיל");
                                                 
                                                $("#shulam").attr("disabled", true);
                                                $("#shulamToAgent").attr("disabled", true);
                                                $("#shulamToMertiaAgent").attr("disabled", true);
                                                $("#agent_commission").val("0")
                                                $("#total_payment").val($("#product_price").val());
                                            }
                                        },
                                        afterSubmit: function(response, postdata) {

                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("מנוי התווסף בהצלחה")
                                            }
                                            else
                                            {
                                                success = false;
                                                alert("מנוי לא התווסף בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }

                                    },
                                    // Delete dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            return {manuy_row: getSelectedCellManuim('manuy_row')};
                                        },
                                        afterSubmit: function(response, postdata) {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("מנוי נמחק בהצלחה")
                                            }
                                            else
                                            {
                                                success = false;
                                                alert("מנוי לא נמחק בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }

                                    },
                                    // Search dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        beforeSearch: function(rp_ge, postdata)
                                        {
                                            return {manuy_number: getSelectedCellManuim('manuy_number')};
                                        }

                                    },
                                    // View dialog parameters
                                    {}
                                    ).navButtonAdd('#manuimPager', {
                                        caption: "ביטול",
                                        id: "cancelBTN",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {

                                            if (!getSelectedCellManuim("person_number"))
                                            {
                                                alert("אתה חייב לבחור מנוי שאותו ברצונך לבטל");
                                            }
                                            else if (getSelectedCellManuim("state") != "פעיל")
                                            {
                                                alert("אפשר לבטל רק מנוי פעיל");
                                            }
                                            else if (getSelectedCellManuim("state") == "פעיל")
                                            {

                                               
                                                openManuimGridDialog(); // לא מעניין אותנו לשלוח את החלק שבוזבז

                                                $.ajax({url: '../gridFunctions/manuimActions.php', // הוצאת התאריך היצירה הראשוני
                                                    data: {oper: 'getFirstCreateDate', manuy_number: getSelectedCellManuim("manuy_number")},
                                                    type: 'post',
                                                    success: function(output)
                                                    {
                                                        if (Date.today().compareTo(Date.parse(output).add(15).day()) === -1)
                                                        { 
                                                           jqgridFormMassage("לא עברו 15 ימים מ " + output + " ולכן המנוי מתבטל ללא תשלום");
                                                            $("#total_payment").val(parseInt(getSelectedCellManuim("total_payment")) * (-1));
                                                            $("#agent_commission").val(parseInt(getSelectedCellManuim("agent_commission")) * (-1));
                                                        }
                                                        else
                                                        {
                                                           /*
                                                             אם יש החזר
                                                     ההחזר קודם כל יורד מהעמלות של הסוכן
                                                        כאשר הסוכן על 0 העמלות יורדות מאיתנו

                                                         אם ההחזר גדול מהעמלה יורדת כל העמלה
                                                     אם הוא קטן מהעמלה יורד ההחזר
            if( returnMoney*(-1)> parseInt(getSelectedCellManuim("agent_commission")) )
                                                        $("#agent_commission").val(parseInt(getSelectedCellManuim("agent_commission")* (-1)));
                                                        else
                                                            $("#agent_commission").val(returnMoney);   
                                                        }
                                                      */
                                                        var moneyWaste= getMoneyWaste();
                                                        var manuyMoneyWaste = moneyWaste['manuyMoneyWaste']; //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var agentAmlotMoneyWaste = moneyWaste['agentAmlotMoneyWaste']; //החלק שבוזבז מהעמלה על מנת לדעת כמה נשאר
                                                       
                                                        var returnMoneyOnManuy =(parseInt(getSelectedCellManuim("total_payment")) - manuyMoneyWaste)* (-1);
                                                        var returnMoneyOnAmla =(parseInt(getSelectedCellManuim("agent_commission")) - agentAmlotMoneyWaste)* (-1);
                                                        jqgridFormMassage("עברו 15 ימים ולכן הלקוח נדרש לשלם את החלק היחסי מהתקופה שעברה");
                                                        $("#total_payment").val(returnMoneyOnManuy);
                                                        $("#agent_commission").val(returnMoneyOnAmla);   
                                                    }
                                                    }
                                                });	//end og ajax call

                                                $("#state").val("מבוטל");
                                                disableAllManuiamFieldsPutToday();
                                            }
                                        },
                                        position: "last"
                                    }).navButtonAdd('#manuimPager', {
                                        id: "freezeBTN",
                                        caption: "הקפאה",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {

                                            if (!getSelectedCellManuim("person_number"))
                                            {
                                                alert("אתה חייב לבחור מנוי שאותו ברצונך להקפיא");
                                            }
                                            else if (getSelectedCellManuim("state") != "פעיל")
                                            {
                                                alert("אפשר להקפיא רק מנוי פעיל");
                                            }
                                            else if (Date.today().between(Date.parse(getSelectedCellManuim("from_2")), Date.parse(getSelectedCellManuim("until"))) == false)
                                            {
                                                alert("אי אפשר להקפיא מנוי שהסתיים או שעוד לא התחיל");
                                            }
                                            else if (getSelectedCellManuim("state") == "פעיל")
                                            {
                                                
                                                   var moneyWaste = getMoneyWaste(); //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var manuyMoneyWaste = moneyWaste['manuyMoneyWaste']; //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var agentAmlotMoneyWaste = moneyWaste['agentAmlotMoneyWaste']; //החלק שבוזבז מהעמלה על מנת לדעת כמה נשאר
                                                    openManuimGridDialog(manuyMoneyWaste,agentAmlotMoneyWaste);

                                                    jqgridFormMassage("במידה והמנוי לא יופשר בתום 45 יום המנוי יתבטל")
                                                    disableAllManuiamFieldsPutToday();
                                                    $("#state").val("קפוא");
                                                    alert(agentAmlotMoneyWaste)
                                                    $("#agent_commission").val(parseInt(getSelectedCellManuim("agent_commission")) - parseInt(agentAmlotMoneyWaste));
                                                    $("#total_payment").val(parseInt(getSelectedCellManuim("total_payment")) - parseInt(manuyMoneyWaste));
                                            }
                                        },
                                        position: "last"
                                    }).navButtonAdd('#manuimPager', {
                                        id: "unFreezeBTN",
                                        caption: "הפשרה",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {

                                            if (!getSelectedCellManuim("person_number"))
                                            {
                                                alert("אתה חייב לבחור מנוי שאותו ברצונך להפשיר");
                                            }
                                            else if (getSelectedCellManuim("state") != "קפוא")
                                            {
                                                alert("אפשר להפשיר רק מנוי קפוא");
                                            }
                                            else if (Date.today().between(Date.parse(getSelectedCellManuim("from_2")), Date.parse(getSelectedCellManuim("from_2")).add(45).day()) == false)
                                            {
                                                alert("אפשר להפשיר רק מנוי שקפוא ללא יותר מ45 יום! מנוי זה צריכים לבטל וליצור חדש.");
                                            }
                                            else if (getSelectedCellManuim("state") == "קפוא")
                                            {
                                                
                                                                                                       

                                                        
                                                
                                                    jqgridFormMassage("מנוי זה יופשר, ובעל המנוי יזוכה על החלק היחסי של תקופת ההקפאה");
                                                   
                                                        /*כאן moneyWaste הוא הכסף שאנחנו צריכים להחזיר
                                                         var agentMoneyWaste=0;
                                                        if( moneyWaste>  parseInt(getSelectedCellManuim("agent_commission")) )
                                                        agentMoneyWaste=parseInt(getSelectedCellManuim("agent_commission"))* (-1);
                                                        else
                                                        agentMoneyWaste=moneyWaste* (-1); */
            
                                                    var moneyWaste = getMoneyWaste(); //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var manuyMoneyWaste = moneyWaste['manuyMoneyWaste']; //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var agentAmlotMoneyWaste = moneyWaste['agentAmlotMoneyWaste']; //החלק שבוזבז מהעמלה על מנת לדעת כמה נשאר
                                                        
                                                    
                                                    openManuimGridDialog(manuyMoneyWaste * (-1),agentAmlotMoneyWaste* (-1));
                                                    $("#total_payment").val(parseInt(getSelectedCellManuim("total_payment")) - manuyMoneyWaste);
                                                    $("#agent_commission").val(parseInt(getSelectedCellManuim("agent_commission")) - agentAmlotMoneyWaste);
                                                    $("#state").val("הפשרה והפעלה");
                                                    disableAllManuiamFieldsPutToday();
                                                
                                            }
                                        },
                                        position: "last"
                                    }).navButtonAdd('#manuimPager', {
                                        id: "reNewBTN",
                                        caption: "חידוש",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {
                                            if (!getSelectedCellManuim("person_number"))
                                            {
                                                alert("אתה חייב לבחור מנוי שאותו ברצונך לחדש");
                                            }
                                            else
                                            {

                                                openManuimGridDialog();
                                                var yearFromEndManuy = Date.parse(getSelectedCellManuim("until")).next().year().toString('yyyy-MM-dd');
                                                $("#from_2").val(getSelectedCellManuim("until"));
                                                $("#until").val(yearFromEndManuy);
                                                $("#state").val("חידוש");
                                                refreshPrice();

                                            }
                                        },
                                        position: "last"
                                    }).navButtonAdd('#manuimPager', {
                                        id: "changeBTN",
                                        caption: "החלפה",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {
                                            if (!getSelectedCellManuim("person_number"))
                                            {
                                                alert("אתה חייב לבחור מנוי שברצונך לבצע בו החלפה");
                                            }
                                            else
                                            {
                                                
                                                jqgridFormMassage("במידה והוחלף גם מם סוג מנוי המחיר היחסי יהיה בהתאם");
                                               var moneyWaste = getMoneyWaste(); //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var manuyMoneyWaste = moneyWaste['manuyMoneyWaste']; //החלק שבוזבז על מנת לדעת כמה נשאר
                                                        var agentAmlotMoneyWaste = moneyWaste['agentAmlotMoneyWaste']; //החלק שבוזבז מהעמלה על מנת לדעת כמה נשאר
                                                    openManuimGridDialog(manuyMoneyWaste,agentAmlotMoneyWaste);
                                                   
                                                    $("#from_2").val(Date.today().toString('yyyy-MM-dd'));
                                                    $("#state").val("החלפה");
                                                //    disableAllManuiamFieldsPutToday();
                                                $("#from_2").attr("disabled", "disabled")
                                                $("#until").attr("disabled", "disabled")
                                                refreshPrice();

                                            }
                                        },
                                        position: "last"
                                    }).navButtonAdd('#manuimPager', {
                                        caption: "דוח מנוי",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {
                                            window.open("print.php?manuyRow=" + getSelectedCellManuim("manuy_row"));
                                        },
                                                position: "last"
                                    }).navButtonAdd('#manuimPager', {
                                        caption: "דוח ממסרים",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {
                                            window.open("memsarim.php?manuyRow=" + getSelectedCellManuim("manuy_row"));
                                        },
                                        position: "last"
                                }).navButtonAdd('#manuimPager', {
                                        caption: "סליקה",
                                        buttonicon: "ui-icon-add",
                                        onClickButton: function() {
                                            window.open("ZCredit/Default.php?manuyRow=" + getSelectedCellManuim("manuy_row") + "&manuy_number=" + getSelectedCellManuim("manuy_number") + "&create_2=" + getSelectedCellManuim("create_2") + "&state=" + getSelectedCellManuim("state") + "&agent_person_number=" + getSelectedCellManuim("agent_person_number") + "&person_number=" + getSelectedCellManuim("person_number") + "&from_2=" + getSelectedCellManuim("from_2") + "&until=" + getSelectedCellManuim("until") + "&manufacturer=" + getSelectedCellManuim("manufacturer") + "&model=" + getSelectedCellManuim("model") + "&license_plate=" + getSelectedCellManuim("license_plate") + "&production_year=" + getSelectedCellManuim("production_year") + "&product_desc=" + getSelectedCellManuim("product_desc")+ "&total_payment=" + getSelectedCellManuim("total_payment"));
                                        },
                                        position: "last"
                                    });
                                    $('#manuimList').jqGrid('filterToolbar', {searchOnEnter: true, enableClear: false});


                                    // put product_desc in the form dialog
                                     $.ajax({url: '../gridFunctions/manuimActions.php',
                                    data: {oper: 'get_Mehiron_Names_With_Prices',mehiron_number:'0' },
                                    type: 'post',
                                    success: function(output)
                                    {
                                        /*	output = output.substr(0, output.length-1); 
                                         output = output.substr(1);
                                         output=output.replace(/{/g,"");
                                         output=output.replace(/}/g,"");
                                         output='{"0":"עצמאי",'+output+"}";*/
                                        //console.log(output);
                                         get_Mehiron_Names_With_PricesJson=eval('(' + output + ')');		   
                                        $("#manuimList").setColProp('product_desc', {editoptions: {value: get_Mehiron_Names_With_PricesJson.names}});
                                       
                                    }
                                });	//end og ajax call
                     
                                    //----------------- end manuim jqgrid

                                    // start checks jqgrid
                                    $("#checksList").jqGrid({
                                        url: "../gridFunctions/checksActions.php",
                                        editurl: "../gridFunctions/checksActions.php",
                                        direction: 'rtl',
                                        async: false,
                                        datatype: 'json',
                                        pager: '#checksPager',
                                        colNames: ['שורה', 'מס מנוי', 'מס צק', 'מס חשבון', 'בנק', 'מס סניף', 'מס בנק', 'תאריך פירעון', 'סכום'],
                                        colModel: [
                                            {name: 'row_num', hidden: true, index: 'row_num', width: 60, editable: true, align: 'right'},
                                            {name: 'manuy2client_manuy_number', index: 'manuy2client_manuy_number', width: 60, editable: true, align: 'right', editrules: {readonly: "readonly", required: true, integer: true}},
                                            {name: 'check_num', index: 'check_num', width: 120, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'acount_num', index: 'acount_num', width: 120, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'bank_name', index: 'bank_name', width: 120, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'snif_number', index: 'snif_number', width: 70, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'bank_num', index: 'bank_num', width: 70, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'repayment_day', index: 'repayment_day', width: 80, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'sum', index: 'sum', width: 60, editable: true, align: 'right', editrules: {required: true, integer: true}}],
                                        rowNum: 20,
                                        rowList: [5, 10, 20, 50],
                                        sortname: 'row_num',
                                        sortorder: "desc",
                                        mtype: "POST",
                                        postData: {oper: 'viewChecksPerManuy'},
                                        viewrecords: true,
                                        imgpath: '../../Scripts/css/Aristo/images',
                                        autowidth: true,
                                        height: "100%"
                                    }); // -- end of   $("#list").jqGrid({

                                    $("#checksList").jqGrid('navGrid', '#checksPager', {edit: true, add: true, del: true, refresh: true, closeAfterAdd: true, reloadAfterSubmit: true, search: false},
                                    // Edit dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        closeAfterEdit: true,
                                        //editData: {person_number: function() {  return "7"; } },
                                 afterShowForm: function() {
                                    
                                         if (!getSelectedCellManuim("person_number"))
                                            {
                                             
                                               $.jgrid.hideModal("#editmodcashList", {gbox: "#gbox_cashList"});
                                               alert("את חייב לבחו מנוי שאליו אתה רוצה להוסיף תשלום");
    
                                            }
                                    
                                        },
                                        beforeShowForm: function() {
                                        if (getSelectedCellManuim("person_number"))
                                       {
                                           checkDate = $('#repayment_day');
                                           checkDate.datepicker({
                                               dateFormat: 'yy-mm-dd'
                                           });
                                           
                                       }

                                        },
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            //            return {person_number: getSelectedCell('person_number')};
                                        },
                                        afterSubmit: function(response, postdata)
                                        {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("פרטי הצק התעדכנו בהצלחה")
                                            }
                                            else
                                            {

                                                success = false;
                                                alert("פרטי הצק לא התעדכנו בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }
                                    },
                                    // Add dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        closeAfterAdd: true,
                                          afterShowForm: function() {
                                    
                                         if (!getSelectedCellManuim("person_number"))
                                            {
                                             
                                               $.jgrid.hideModal("#editmodcashList", {gbox: "#gbox_cashList"});
                                               alert("את חייב לבחו מנוי שאליו אתה רוצה להוסיף תשלום");
    
                                            }
                                    
                                        },
                                        beforeShowForm: function() {
                                    
                                            if (getSelectedCellManuim("person_number"))
                                            {
                                            checkDate = $('#repayment_day');
                                            checkDate.datepicker({
                                                dateFormat: 'yy-mm-dd'
                                            });
                                            $("#manuy2client_manuy_number").val(getSelectedCellManuim("manuy_number"));
                                            }
                                        },
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            //            return {person_number: getSelectedCell('person_number')};
                                        },
                                        afterSubmit: function(response, postdata)
                                        {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("פרטי הצק התווספו בהצלחה")
                                            }
                                            else
                                            {

                                                success = false;
                                                alert("פרטי הצק לא התווספו בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }
                                    },
                                    // Delete dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            // return {person_number: getSelectedCell('person_number')};
                                        },
                                        afterSubmit: function(response, postdata) {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("צק נמחק בהצלחה")
                                            }
                                            else
                                            {
                                                success = false;
                                                alert("צק לא נמחק בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }

                                    },
                                    // Search dialog parameters
                                    {},
                                            // View dialog parameters
                                                    {}
                                            );
                                            $('#checksList').jqGrid('filterToolbar', {searchOnEnter: true, enableClear: false});

                                            // end checks jqgrid


                                    // start mezuman jqgrid
                                    $("#cashList").jqGrid({
                                        url: "../gridFunctions/cashActions.php",
                                        editurl: "../gridFunctions/cashActions.php",
                                        direction: 'rtl',
                                        async: false,
                                        datatype: 'json',
                                        pager: '#cashPager',
                                   
                                        colNames: ['שורה', 'מס מנוי', 'נוצר', 'סכום', 'התקבל ב'],
                                        colModel: [
                                            {name: 'row_num', hidden: true, index: 'row_num', width: 60, editable: true, align: 'right'},
                                            {name: 'manuy2client_manuy_number', index: 'manuy2client_manuy_number', width: 60, editable: true, align: 'right', editrules: {readonly: "readonly", required: true, integer: true}},
                                            {name: 'create_2', index: 'create_2', width: 120, editable: true, align: 'right', editrules: {readonly: "readonly",required: true}},
                                            {name: 'amount', index: 'amount', width: 120, editable: true, align: 'right', editrules: {required: true}},
                                            {name: 'recived', index: 'recived', width: 120, editable: true, align: 'right', editrules: {required: true}}
                                        ],
                                        rowNum: 20,
                                        rowList: [5, 10, 20, 50],
                                        sortname: 'row_num',
                                        sortorder: "desc",
                                        mtype: "POST",
                                        postData: {oper: 'viewCashPerManuy'},
                                        viewrecords: true,
                                        imgpath: '../../Scripts/css/Aristo/images',
                                        autowidth: true,
                                        height: "100%"
                                    }); // -- end of   $("#list").jqGrid({

                                    $("#cashList").jqGrid('navGrid', '#cashPager', {edit: true, add: true, del: true, refresh: true, closeAfterAdd: true, reloadAfterSubmit: true, search: false},
                                    // Edit dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        closeAfterEdit: true,
                                        //editData: {person_number: function() {  return "7"; } },
                                  afterShowForm: function() {
                                    
                                         if (!getSelectedCellManuim("person_number"))
                                            {
                                             
                                               $.jgrid.hideModal("#editmodcashList", {gbox: "#gbox_cashList"});
                                               alert("את חייב לבחו מנוי שאליו אתה רוצה להוסיף תשלום");
    
                                            }
                                    
                                        },
                                        beforeShowForm: function() {
                                             if (getSelectedCellManuim("person_number"))
                                            {
                                                $("#create_2").val(Date.today().toString('yyyy-MM-dd'));
                                                $("#create_2").attr("disabled", true)
                                                checkDate = $('#recived');
                                                checkDate.datepicker({
                                                    dateFormat: 'yy-mm-dd'
                                                });
                                                 $("#manuy2client_manuy_number").val(getSelectedCellManuim("manuy_number"));
                                            }
                                            

                                        },
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            //            return {person_number: getSelectedCell('person_number')};
                                        },
                                        afterSubmit: function(response, postdata)
                                        {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("פרטי המזומן התעדכנו בהצלחה")
                                            }
                                            else
                                            {

                                                success = false;
                                                alert("פרטי המזומן לא התעדכנו בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }
                                    },
                                    // Add dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        closeAfterAdd: true,
                                        afterShowForm: function() {
                                    
                                         if (!getSelectedCellManuim("person_number"))
                                            {
                                             
                                               $.jgrid.hideModal("#editmodcashList", {gbox: "#gbox_cashList"});
                                                 alert("את חייב לבחו מנוי שאליו אתה רוצה להוסיף תשלום");
    
                                            }
                                    
                                        },
                                        beforeShowForm: function() {
                                    
                                                $("#create_2").val(Date.today().toString('yyyy-MM-dd'));
                                                $("#create_2").attr("disabled", true)
                                                checkDate = $('#recived');
                                                checkDate.datepicker({
                                                    dateFormat: 'yy-mm-dd'
                                                });
                                           $("#manuy2client_manuy_number").val(getSelectedCellManuim("manuy_number"));
                                        },
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            //            return {person_number: getSelectedCell('person_number')};
                                        },
                                        afterSubmit: function(response, postdata)
                                        {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("פרטי המזומן התווספו בהצלחה")
                                            }
                                            else
                                            {

                                                success = false;
                                                alert("פרטי המזומן לא התווספו בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }
                                    },
                                    // Delete dialog parameters
                                    {
                                        reloadAfterSubmit: true,
                                        onclickSubmit: function(rp_ge, postdata)
                                        {
                                            // return {person_number: getSelectedCell('person_number')};
                                        },
                                        afterSubmit: function(response, postdata) {
                                            if (response.responseText == "ok")
                                            {
                                                success = true;
                                                alert("המזומן נמחק בהצלחה")
                                            }
                                            else
                                            {
                                                success = false;
                                                alert("המזומן לא נמחק בהצלחה")
                                            }
                                            return [success, response.responseText]
                                        }

                                    },
                                    // Search dialog parameters
                                    {},
                                            // View dialog parameters
                                                    {}
                                            );
                                            $('#cashList').jqGrid('filterToolbar', {searchOnEnter: true, enableClear: false});

                                            // end mezuman jqgrid








                        // start credit jqgrid
                                    $("#creditList").jqGrid({
                                        url: "../gridFunctions/creditActions.php",
                                        editurl: "../gridFunctions/cashActions.php",
                                        direction: 'rtl',
                                        async: false,
                                        datatype: 'json',
                                        pager: '#creditPager',
                                       
                                        colNames: ['שורה', 'נוצר', 'סכום', 'תשלומים', 'שורת מנוי', 'מס מנוי'],
                                        colModel: [
                                            {name: 'slikot_row', hidden: true, index: 'slikot_row', width: 60, editable: true, align: 'right'},
                                            {name: 'create', index: 'create', width: 60, editable: true, align: 'right'},
                                            {name: 'Sum', index: 'Sum', width: 60, editable: true, align: 'right'},
                                            {name: 'Payments', index: 'Payments', width: 120, editable: true, align: 'right'},
                                            {name: 'manuy_row', index: 'manuy_row', width: 120, editable: true, align: 'right'},
                                            {name: 'manuy_number', index: 'manuy_number', width: 120, editable: true, align: 'right'}
                                        ],
                                        rowNum: 20,
                                        rowList: [5, 10, 20, 50],
                                        sortname: 'create',
                                        sortorder: "desc",
                                        mtype: "POST",
                                        postData: {oper: 'viewCreditPerManuy'},
                                        viewrecords: true,
                                        imgpath: '../../Scripts/css/Aristo/images',
                                        autowidth: true,
                                        height: "100%"
                                    }); // -- end of   $("#list").jqGrid({

                                            $('#creditList').jqGrid('filterToolbar', {searchOnEnter: true, enableClear: false});

                                            // end mezuman jqgrid







   //------------------------------------datepicker for manuim search
                                        
                                        
                                        
                                        
                                        
                                        
                                   var  checkInDateInManuimSearch = $($("[id=gs_from_2]")[0]);
                                       var     checkOutDateInManuimSearch = $($("[id=gs_until]")[0]);
                                            checkInDateInManuimSearch.datepicker({
                                                dateFormat: 'yy-mm-dd',
                                            });

                                            checkOutDateInManuimSearch.datepicker({
                                                dateFormat: 'yy-mm-dd',
                                            });
                                    
                                            checkInDateInManuimSearch.datepicker('setDate', new Date().add(-1).year());
                                            checkOutDateInManuimSearch.datepicker('setDate', new Date().add(1).year());
                                            
                                           
                                            
                                         
                                            
                                            
     function swapElements(elm1, elm2) {
    var parent1, next1,
        parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}
swapElements($("#manuimPager_left")[0], $("#manuimPager_right")[0]);

swapElements($("#checksPager_left")[0], $("#checksPager_right")[0]);
swapElements($("#cashPager_left")[0], $("#cashPager_right")[0]);

 jQuery("#manuimList").trigger('reloadGrid');
                                    //-----------------------------------
                                 //   $("#clientGrid").hide();
                                        });// -- end of  $(document).ready(function ()
                                        var b = 3;
                                       
                                function getSelectedCell(str)
                                {
                                    var grid = jQuery('#clientList');
                                    var sel_id = grid.jqGrid('getGridParam', 'selrow');
                                    var myCellData = grid.jqGrid('getCell', sel_id, str);
                                    return myCellData;
                                }
                                function getSelectedCellManuim(str)
                                {
                                    var grid = jQuery('#manuimList');
                                    var sel_id = grid.jqGrid('getGridParam', 'selrow');
                                    var myCellData = grid.jqGrid('getCell', sel_id, str);
                                    return myCellData;
                                }


                                function enableBTN()
                                {
                                    $("#cancelBTN").removeClass('ui-state-disabled'); //Enable 
                                    $("#freezeBTN").removeClass('ui-state-disabled'); //Enable 
                                    $("#unFreezeBTN").removeClass('ui-state-disabled'); //Enable 
                                    $("#reNewBTN").removeClass('ui-state-disabled'); //Enable 
                                    $("#changeBTN").removeClass('ui-state-disabled'); //Enable 
                                }

                                function disableBTN()
                                {
                                    $("#cancelBTN").addClass('ui-state-disabled'); //Enable 
                                    $("#freezeBTN").addClass('ui-state-disabled'); //Enable 
                                    $("#unFreezeBTN").addClass('ui-state-disabled'); //Enable 
                                    $("#reNewBTN").addClass('ui-state-disabled'); //Enable 
                                    $("#changeBTN").addClass('ui-state-disabled'); //Enable 

                                }

                                function openManuimGridDialog(manuyMoneyWaste,agentAmlotMoneyWaste)
                                {
                                    if(manuyMoneyWaste== 'undefined') manuyMoneyWaste=false;
                                    if(agentAmlotMoneyWaste== 'undefined') agentAmlotMoneyWaste=false;

                                    var grid = jQuery("#manuimList");
                                    var rowKey = grid.getGridParam("selrow");
                                    grid.editGridRow(rowKey, {reloadAfterSubmit: true, closeAfterEdit: true, closeAfterAdd: true, recreateForm: true, width: 450, onclickSubmit: function(rp_ge, postdata)
                                        {
                                            return {product_desc: $("#product_desc option:selected").text(), manuy_row: getSelectedCellManuim('manuy_row'), oper: "add",manuyMoneyWaste: manuyMoneyWaste, agentAmlotMoneyWaste: agentAmlotMoneyWaste, totalPaymentBefore: getSelectedCellManuim("total_payment"), totalComistionBefore: getSelectedCellManuim("agent_commission")};
                                        }});
                                    $(".navButton").hide();

                                }

                                function getMoneyWaste()
                                {
                                 var a = Date.today();
                                var b = Date.parse(getSelectedCellManuim("from_2"));
                                var c = Date.parse(getSelectedCellManuim("until"));
                                var manuyDuration = new TimeSpan(c - b);
                                var daysPast = new TimeSpan(a - b);
                                var manuyMoneyWaste= parseInt(getSelectedCellManuim("total_payment")) / (manuyDuration.days) * (daysPast.days);
                                var agentAmlotMoneyWaste= parseInt(getSelectedCellManuim("agent_commission")) / (manuyDuration.days) * (daysPast.days);
                                 return {manuyMoneyWaste:manuyMoneyWaste,agentAmlotMoneyWaste:agentAmlotMoneyWaste}
                                }


                                function jqgridFormMassage(str)
                                {
                                    $(".tinfo").show();
                                    $(".topinfo").addClass("ui-state-highlight ui-corner-all");
                                    $(".topinfo").html(str);
                                }
                                function getFirstCreateDate()
                                {
                                    //  var firstDate=false;
                                    return   $.ajax({url: '../gridFunctions/manuimActions.php',
                                        data: {oper: 'getFirstCreateDate', manuy_number: getSelectedCellManuim("manuy_number")},
                                        type: 'post',
                                        success: function(output)
                                        {
                                            //       console.log("output " + output);
                                            //    firstDate=output;
                                            // console.log(output)
                                            return output.responseText;

                                        }
                                    });	//end og ajax call
                                    //   console.log("firstDate " + firstDate);

                                    //   return firstDate;
                                }
                                
                                
                                
                                function searchPersonInGrid(personId)
                                {
                                    $($("[id=gs_person_number]")[0]).val(personId);
                                    var sgrid = $("#clientList")[0];
                                    sgrid.triggerToolbar();
                                    
                                    
                                    
                                    
                                    
                                }
                                
                                function disableAllManuiamFieldsPutToday()
                                {
                                    $("#from_2").val(Date.today().toString('yyyy-MM-dd'));
                                    $("#from_2").attr("disabled", true)
                                    $("#until").attr("disabled", true)
                                    $("#manufacturer").attr("disabled", true)
                                    $("#model").attr("disabled", true)
                                    $("#license_plate").attr("disabled", true)
                                    $("#production_year").attr("disabled", true)
                                    $("#total_payment").attr("disabled", true)
                                    $("#product_desc").attr("disabled", true)
                                    $("#paymen_type").attr("disabled", true)
                                    $("#from_agent_commission").attr("disabled", true);
                                    $("#shulam").attr("disabled", true);

                                }
                                var exsitVar=false;
                                function findOrAddClient()
                                {
                                     
                                 exsitVar= $.ajax({url: '../gridFunctions/personActions.php',
                                        data: {oper: 'personExsit', person_id: $("#clientId").val()},
                                        type: 'post',
                                        async: false,
                                        success: function(output)
                                        {
                                            //       console.log("output " + output);
                                            //    firstDate=output;
                                            // console.log(output)
                                            if (output=="FALSE")
                                                {
                                                $("#addClientBTN").click();
                                                $("#person_id").val($("#clientId").val());
                                                $("#clientGrid").hide();
                                                }
                                            else
                                                {
                                                searchPersonInGrid(output) ;
                                                $("#clientGrid").show();
                                                }
                                            return output;

                                        }
                                    });	//end og ajax call
                                    
                                    
                                    //alert(exsitVar.responseText);

                                }



                    </script>
                    </head>
                    <body dir="rtl"  style="padding:0px; margin:0px;">
                        <div id="main" >
                              <?php include("adminHeader.php"); ?>
                            
                            <h1>מנויים</h1>  
                            <div id="lc">
                                <table id="manuimList" class="scroll" cellpadding="0" cellspacing="0"></table>
                                <div id="manuimPager" class="scroll" style="text-align: center;"> </div>
                            </div>
                            
                                
                            <div id="checksContainer">
                                <h1>צ'קים</h1>  
                                <div id="lc">
                                    <table id="checksList" class="scroll" cellpadding="0" cellspacing="0"></table>
                                    <div id="checksPager" class="scroll" style="text-align: center;"> </div>
                                </div>
                            </div>
                                
                                
                            <div id="cashContainer">
                                <h1>מזומן</h1>  
                                <div id="lc">
                                    <table id="cashList" class="scroll" cellpadding="0" cellspacing="0"></table>
                                    <div id="cashPager" class="scroll" style="text-align: center;"> </div>
                                </div>
                            </div>
                                
                            <div id="creditContainer">
                                <h1>אשראי</h1>  
                                <div id="lc">
                                    <table id="creditList" class="scroll" cellpadding="0" cellspacing="0"></table>
                                    <div id="creditPager" class="scroll" style="text-align: center;"> </div>
                                </div>
                            </div>


                            <?php include("../footer.php"); ?>	
                        </div>

                    </body>
                    </html>